﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace AesDemo
{
    class RSAManager : IRSAManager
    {
        /// <summary>
        /// 生成私钥
        /// </summary>
        /// <returns>私钥base64字符串</returns>
        public string CreatePrivateKey()
        {
            var Rsa = new RSACryptoServiceProvider();
            var priKey = Convert.ToBase64String(Rsa.ExportCspBlob(true));
            return priKey;
        }
        /// <summary>
        /// 生成私钥
        /// </summary>
        /// <param name="dwKeySize">私钥位数</param>
        /// <returns>私钥base64字符串</returns>
        public string CreatePrivateKey(int dwKeySize)
        {
            var Rsa = new RSACryptoServiceProvider(dwKeySize);
            var priKey = Convert.ToBase64String(Rsa.ExportCspBlob(true));
            return priKey;
        }
        /// <summary>
        /// 获取公钥
        /// </summary>
        /// <param name="priKey">私钥base64字符串</param>
        /// <returns>公钥base64字符串</returns>
        public string GetPublicKey(string priKey)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.ImportCspBlob(Convert.FromBase64String(priKey));
            var pubKey = Convert.ToBase64String(rsa.ExportCspBlob(false));
            return pubKey;
        }
        /// <summary>
        /// 签名数据
        /// </summary>
        /// <param name="priKey">私钥字符串</param>
        /// <param name="data">待签名内容</param>
        /// <returns>签名后字符串</returns>
        public string SignData(string priKey, string data)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.ImportCspBlob(Convert.FromBase64String(priKey));

            var signData = rsa.SignData(Encoding.UTF8.GetBytes(data), new SHA1CryptoServiceProvider());
            return Convert.ToBase64String(signData);
        }
        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="pubKey">公钥字符串</param>
        /// <param name="signedData">签名后字符串</param>
        /// <param name="data">待验证签名内容</param>
        /// <returns>是否验证通过</returns>
        public bool VerifySignedData(string pubKey, string signedData, string data)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.ImportCspBlob(Convert.FromBase64String(pubKey));

            var verify = rsa.VerifyData(Encoding.UTF8.GetBytes(data), new SHA1CryptoServiceProvider(), Convert.FromBase64String(signedData));
            return verify;
        }

    }
}
